/**
 * Created by liguangsong on 16/8/16.
 */
$(document).ready(function () {
    $(".time").text(moment().format("YYYY年MM月DD日 HH:mm:ss"));
    var localData = getLocalData();
    getBuyList(localData);
    getGiftList(localData);
    computePrice(localData);
    addConfirmButton();

});

function computePrice(localData) {
    var total = getPrice(localData, "total");
    $("#total_price").text(total.toFixed(2));
    var econnomize = getPrice(localData, "Econnomize") - total;
    $("#econnomize_price").text(econnomize.toFixed(2));
}

function selectGiftTemplate(info, template) {
    var count = info["count"];
    var tr = null;
    if(count > 2 && info["type"] != "杂货" && info["type"] != "珍宝") {
        tr = template.replace(/name/, info["name"]).replace(/type/, info["type"])
            .replace(/count/, parseInt(count / 3));
        return tr;
    }
    return tr;
}


function getBuyList(localData) {
    var template = $("#buy_template").html();
    _.times(localData.length, function (i) {
        var tr = template.replace(/name/, localData[i]["name"]).replace(/type/, localData[i]["type"])
            .replace(/price/, localData[i]["price"]).replace(/unit/, localData[i]["unit"])
            .replace(/count/, localData[i]["count"]).replace(/subtotal/, localData[i]["subtotal"]);
        $("#buy_list_body").append(tr);
    })
}



function getGiftList(localData) {
    var template = $("#gift_template").html();
    _.times(localData.length, function (i) {
        var tr = selectGiftTemplate(localData[i], template);
        $("#gift_list_body").append(tr);
    })
}


function getPrice(localData, type) {
    var total = 0;
    _.times(localData.length, function(index) {
        var data = localData[index]["subtotal"];
        var markPosition = (type=="Econnomize")? data.lastIndexOf("元"): data.indexOf("元");
        var pricePosition = (type=="Econnomize")? data.indexOf("：") + 1: 0;
        var subTotal = data.substring(pricePosition, markPosition);
        total += parseFloat(subTotal);

    });
    return total;
}


function addConfirmButton() {
    $("#confirm button").click(function() {
        console.log("clear");
        window.localStorage.clear();
        window.location.href = "./goodsList.html";
    })

}